package com.heima.wemedia.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.applet.AppletContext;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Transactional
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //检查参数（multipartFile  校验图片格式     用户是否登录）
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的文件");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //上传文件到阿里云OSS
        //文件名称：获取原始后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新文件名称： 随机生产UUID+后缀
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = uuid + suffix;
        //调用上传方法
        try {
             //文件在OSS中的全路径
            String store = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            //创建Material实体类
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());//登录用户ID
            wmMaterial.setUrl(store);//OSS路径
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            //保存素材
            save(wmMaterial);
            //返回结果   需要再URL上添加访问前缀 用于前端回显图片

            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传文件失败，失败原因：====》"+e.getMessage());
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"服务端出现异常，上传失败");
        }

  /*  @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, filename+suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite+fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }
    *//**
         * 检查文件格式
         * @param path
         * @return
         *//*
    private boolean checkFileSuffix(String path){
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }*/
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
       //参数校验
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }


        //封装查询参数
        //分页参数
        IPage<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //查询参数
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection() != null &&dto.getIsCollection().intValue() ==1) {
            queryWrapper.eq(WmMaterial::getIsCollection, WemediaConstants.COLLECT_MATERIAL);
        }

        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageResult  = page(pageReq,queryWrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal());

        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        responseResult.setData(records);
        return responseResult;
    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        //检查ID
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询该素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材已被引用，无法删除");
        }
        //查询素材信息  ==》URL（OSS路径）
        WmMaterial material = getById(id);
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除对应oss文件
        fileStorageService.delete(material.getUrl());
        //删除素材数据
        removeById(id);
        return ResponseResult.okResult();
    }

    /**
     *
     * @param id 素材ID
     * @param type  0 不收藏，1 收藏
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检查参数 登录  只能收藏自己上传的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        update(Wrappers.<WmMaterial>lambdaUpdate().
                set(WmMaterial::getIsCollection,type).
                eq(WmMaterial::getId,id).
                eq(WmMaterial::getUserId,user.getId()));

        return ResponseResult.okResult();
    }
}

